package com.wx.rabbitmq.message;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.QueueingConsumer;
import com.wx.rabbitmq.MqConnection;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * @ClassName Consumers
 * @Author wx
 * @Description 消费者-消息体定义
 * @Date 2018-11-22-22:31
 */
public class Consumers {
    public static void main(String[] agrs) throws IOException, TimeoutException, InterruptedException {
        //1.获取connection
        Connection connection = MqConnection.getConnection();

        //2.通过connection创建一个Channel
        Channel channel = connection.createChannel();

        //3. 声明（创建）一个队列
        String queueName = "test001";

        /**
         * queue=队列名称、durable=队列是否持久化、exclusive=队列是否顺序消费(相当于加了一把独占锁，此队列只能同时被一个连接访问)
         * autoDelete=如果该队列没有绑定交换机则自动删除、arguments=额外参数
         */
        channel.queueDeclare(queueName, true, false, false, null);

        //4. 创建消费者
        QueueingConsumer queueingConsumer = new QueueingConsumer(channel);

        //5. 设置Channel  queue=访问的队列名称、autoAck=是否自动签收、callback=具体消费者对象
        channel.basicConsume(queueName, true, queueingConsumer);

        while(true){
            //6 获取消息
            QueueingConsumer.Delivery delivery = queueingConsumer.nextDelivery();
            String msg = new String(delivery.getBody());
            System.err.println("消费端: " + msg);
            Map<String, Object> headers = delivery.getProperties().getHeaders();
            System.err.println("自定义消息"+headers.toString());
        }

    }
}
